import { SET_TODO, SET_TODO_LIST, REMOVE_TODO, SET_STATUS ,SET_DOING} from '@/store/actionsType';
import { ITodo, TODO_STATUS } from '@/typeings';
import { watch } from 'vue';
import { Store, useStore } from 'vuex'
import { IUseLocalStorage, useLocalStorage } from './localStorage'


export interface IUseTodo {
    setTodo: ( value : string ) => void ;
    setTodoList: () => void ;
    removeTodo: (id : number) => void ;
    setStatus: (id : number) => void ;
    setDoing: (id : number) => void ;
}

function useTodo () : IUseTodo {

    const store : Store<any> = useStore()
    const { GetLocalList , SetLocalList } : IUseLocalStorage = useLocalStorage()
    const todoList : ITodo[] = GetLocalList()


    watch( ()=>{
        return store.state.list
    }, (todoList) => {
        SetLocalList(todoList)
    } )
    
    // 设置数据到 localStorage 里面
    function setTodo ( value : string ) : void {
        const todo  : ITodo = {
            id : new Date().getTime(),
            content : value ,
            status : TODO_STATUS.WillDo
        }

        store.dispatch(SET_TODO, todo)
        
    }

    // 从  localStorage  里面取
    function setTodoList () {
        store.dispatch(SET_TODO_LIST, todoList)
    }


    function removeTodo ( id : number) : void {
        store.dispatch(REMOVE_TODO, id)
        
    }


    function setStatus (id : number) : void {
        store.dispatch(SET_STATUS, id)
        
    }


    function setDoing (id : number) : void {
        store.dispatch(SET_DOING, id)
        
    }

    

    return {
        setTodo,
        setTodoList,
        removeTodo,
        setStatus,
        setDoing
    }
}


export {
    useTodo
}